import 'package:cave_flutter/common/chat_manager.dart';
import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nertc_core/nertc_core.dart';

import '../../../common/chat_rtc_manager.dart';
import '../../whl_main/whl_main_logic.dart';
import 'chat_call_logic.dart';

class Chat_callPage extends StatelessWidget {
  Chat_callPage({Key? key}) : super(key: key);

  final logic = Get.put(Chat_callLogic());

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        onPopInvoked: (canPop) {
          // print(canPop);
          if (canPop) {
            return;
          }
          logic.backAction();
        },
        child: Scaffold(
          body: GetBuilder<Chat_callLogic>(builder: (logic) {
            return logic.isVideoCall ? videoCallView() : audioCallView();
          }),
        ));
  }

  Widget audioCallView() {
    return UIStack(
      children: [
        Hero(
          tag: "videoCall",
          child: UIImage(
            httpImage: logic.userModel?.avatar?.toImageUrl(),
            assetPlaceHolder: WHLGlobalConfig.userPlaceholderAvatar,
            width: ScreenUtil().screenWidth,
            height: ScreenUtil().screenHeight,
            fit: BoxFit.cover,
          ),
        ),
        visualEffectWidget(
            width: ScreenUtil().screenWidth,
            height: ScreenUtil().screenHeight,
            color: kAppColor("#393939"),
            opacity: 0.77),
        UIColumn(
          margin: EdgeInsets.only(
              left: 7.w, top: ScreenUtil().statusBarHeight + 11.h),
          padding: EdgeInsets.symmetric(horizontal: 13.w),
          children: [
            UIRow(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UIImage(
                  padding: EdgeInsets.all(5.w),
                  assetImage: "chat_sx",
                  imageColor: kAppWhiteColor,
                  width: 30.w,
                  height: 30.w,
                  onTap: () {
                    logic.backAction();
                  },
                ),
                Expanded(
                    child: UIText(
                  margin: EdgeInsets.only(left: 10.w, right: 40.w),
                  height: 30.w,
                  text: "已热聊 ${(ChatRTCManager.getInstance().callTime~/60).toString().padLeft(2,'0')}:${(ChatRTCManager.getInstance().callTime%60).toString().padLeft(2,'0')}",
                  fontSize: 16.sp,
                  textColor: kAppWhiteColor,
                  alignment: Alignment.center,
                ))
              ],
            ),
            UIButton(
              margin: EdgeInsets.only(top: 150.h, bottom: 17.h),
              logic.userModel?.nickName??"",
              titleColor: kAppWhiteColor,
              titleFont: 20.sp,
              httpImage: logic.userModel?.avatar?.toImageUrl(),
              assetPlaceHolder: WHLGlobalConfig.userPlaceholderAvatar,
              imageTitleSpace: 12.h,
              imageWidth: 94.w,
              imageHeight: 94.w,
              imageRadius: 47.w,
              imageFit: BoxFit.cover,
              buttonType: MyButtonType.imageInTop,
            ),
          ],
        ),
        Positioned(
            bottom: 60.h, left: 30.w, right: 30.w, child: footAllBtnView()),
      ],
    );
  }

  Widget videoCallView() {
    RtcUserSession? firstSession;
    if (logic.remoteSessions.isNotEmpty) {
      firstSession = logic.remoteSessions.first;
    }
    RtcUserSession? lastSession;
    if (logic.remoteSessions.length > 1) {
      lastSession = logic.remoteSessions.last;
    }
    return UIStack(
      children: [
        Hero(
          tag: "videoCall",
          child: firstSession != null
              ? NERtcVideoView.withInternalRenderer(
                  uid: firstSession.uid == logic.uid ? null : firstSession.uid,
                  subStream: firstSession.subStream,
                  mirrorListenable: firstSession.mirror,
                  rendererEventLister: ChatRTCManager.getInstance(),
                  fitType: NERtcVideoViewFitType.cover,
                )
              : const UIContainer(),
        ),
        UIColumn(
          margin: EdgeInsets.only(
              left: 7.w, top: ScreenUtil().statusBarHeight + 11.h),
          padding: EdgeInsets.symmetric(horizontal: 13.w),
          children: [
            UIRow(
              children: [
                UIRow(
                  mainAxisSize: MainAxisSize.min,
                  color: kAppBlackColor.withOpacity(0.19),
                  radius: 20.w,
                  children: [
                    UIImage(
                      margin: EdgeInsets.all(2.w),
                      httpImage: logic.userModel?.avatar?.toImageUrl(),
                      assetPlaceHolder: WHLGlobalConfig.userPlaceholderAvatar,
                      width: 36.w,
                      height: 36.w,
                      radius: 18.w,
                      fit: BoxFit.cover,
                    ),
                    UIText(
                      margin: EdgeInsets.symmetric(horizontal: 4.w),
                      text: logic.userModel?.nickName,
                      textColor: kAppWhiteColor,
                      fontSize: 13.sp,
                    ),
                    UIText(
                      margin: EdgeInsets.only(right: 2.w),
                      color: kAppBlackColor,
                      alignment: Alignment.center,
                      text: "关注",
                      width: 41.w,
                      height: 28.w,
                      radius: 14.w,
                      textColor: kAppWhiteColor,
                      fontSize: 13.sp,
                    )
                  ],
                ),
                Expanded(child: UIContainer()),
                UIImage(
                  margin: EdgeInsets.only(right: 4.w),
                  assetImage: "chat_sx",
                  width: 30.w,
                  height: 30.w,
                  radius: 15.w,
                  onTap: () {
                    logic.backAction();
                  },
                ),
              ],
            ),
            UIRow(
              margin: EdgeInsets.only(top: 13.h),
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UIText(
                  padding: EdgeInsets.symmetric(horizontal: 9.w),
                  color: kAppBlackColor.withOpacity(0.19),
                  alignment: Alignment.center,
                  height: 24.w,
                  radius: 12.w,
                  text: "通话时长  ${(ChatRTCManager.getInstance().callTime~/60).toString().padLeft(2,'0')}:${(ChatRTCManager.getInstance().callTime%60).toString().padLeft(2,'0')}",
                  fontSize: 11.sp,
                  textColor: kAppWhiteColor,
                ),
                Expanded(child: UIContainer()),
                if (lastSession != null)
                  UIContainer(
                    margin: EdgeInsets.only(top: 4.h),
                    width: 84.w,
                    height: 110.h,
                    radius: 6.w,
                    color: kAppBlackColor.withOpacity(0.38),
                    child: NERtcVideoView.withInternalRenderer(
                      uid:
                          lastSession.uid == logic.uid ? null : lastSession.uid,
                      subStream: lastSession.subStream,
                      mirrorListenable: lastSession.mirror,
                      rendererEventLister: ChatRTCManager.getInstance(),
                      fitType: NERtcVideoViewFitType.cover,
                    ),
                    onTap: (){
                      logic.remoteSessions = logic.remoteSessions.reversed.toList();
                      logic.update();
                    },
                  )
              ],
            )
          ],
        ),
        Positioned(
            bottom: 60.h, left: 30.w, right: 30.w, child: footAllBtnView()),
      ],
    );
  }

  Widget footAllBtnView() {
    return UIColumn(
      children: [
        moreBtnGridView(),
        UIButton("挂断",
            buttonType: MyButtonType.imageInTop,
            margin: EdgeInsets.only(top: 30.h),
            titleFont: 14.sp,
            titleColor: kAppWhiteColor,
            assetImageName: "chat_callGD",
            imageWidth: 62.w,
            imageHeight: 62.w,
            imageTitleSpace: 13.h, onTap: () {
          logic.endCall();
        }),
      ],
    );
  }

  Widget moreBtnGridView() {
    return UIContainer(
      height: 84.w,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: logic.callMoreBtnTitles.length < 4 ? 45.w : 14.w,
          mainAxisExtent: 52.w,
        ),
        itemBuilder: (context, index) {
          Map dic = logic.callMoreBtnTitles[index];
          CallMoreBtnType type = dic["type"];
          bool isSelect = false;
          if (type == CallMoreBtnType.closeVoice) {
            print("11111${logic.isAudioEnabled}");
            isSelect = logic.isAudioEnabled;
          } else if (type == CallMoreBtnType.sound) {
            isSelect = logic.isSpeakerEnabled;
          }
          return UIColumn(
            children: [
              UIContainer(
                padding: EdgeInsets.all(12.w),
                color: isSelect
                    ? kAppWhiteColor
                    : kAppBlackColor.withOpacity(0.19),
                width: 52.w,
                height: 52.w,
                radius: 26.w,
                child: UIImage(
                  assetImage: dic["image"],
                  imageColor: isSelect ? kAppTwoTextColor : kAppWhiteColor,
                ),
              ),
              UIText(
                margin: EdgeInsets.only(top: 8.w),
                text: dic["title"],
                textColor: kAppWhiteColor,
                fontSize: 13.sp,
              )
            ],
            onTap: () {
              logic.moreBtnAction(type);
            },
          );
        },
        itemCount: logic.callMoreBtnTitles.length,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}
